package com.example.demo.controller;

import com.example.demo.domain.User;
import com.example.demo.service.UserService;
import com.example.demo.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class enrollController
{
    @Value("${ip}")
    private String ip;
    @Value("${server.port}")
    private String port;
    @Value("${uploadGoodsPath}")
    private String uploadGoodsPath;
    @Value("${uploadIconPath}")
    private String uploadIconPath;
    @Value("${goodsPicPathPattern}")
    private String goodsPicPathPattern;
    @Value("${iconPathPattern}")
    private String iconPathPattern;
    @Resource
    private UserService userService;
    @RequestMapping("/userEnroll")
    public String Login(@RequestParam(name="username",required = false)String username,
                        @RequestParam(name="password",required = false)String password,
                        @RequestParam(name="phone",required = false)String phone,
                        RedirectAttributes model, HttpServletRequest request)
    {
        User user=userService.getUserByUserName(username);
        request.getSession().setAttribute("goodsPicPath", "http://"+ip+":"+port+goodsPicPathPattern);
        request.getSession().setAttribute("iconPathPattern", "http://"+ip+":"+port+iconPathPattern);
        if(user!=null)
        {
            model.addFlashAttribute("enrollMsg", "用户名已被注册");
        }
        else
        {
            user=new User();
            user.setUsername(username);
            user.setPwd(password);
            user.setPhone(phone);
            user.setIconURL("default.png");
            user.setAddress("");
            user.setState(0);
            user.setTimes(TimeUtils.getStringDate());
            userService.addUser(user);
            request.getSession().setAttribute("user",userService.getUserByUserName(username));
            model.addFlashAttribute("enrollSuccessMsg", "注册成功（点击 x 跳转)");
        }
        return "redirect:/enroll";
    }
}
